require 'rbconfig'
require 'fileutils'

include Config

class ProcesosController < ApplicationController
  # GET /procesos
  # GET /procesos.json
  before_filter :authenticate_user!


  def index
    @procesos = Proceso.all.sort_by(&:created_at).reverse

    @proceso = Proceso.new

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @procesos }
    end
  end



  # GET /procesos/1
  # GET /procesos/1.json
  def show
    @proceso = Proceso.find(params[:id])
    @proyecto=Proyecto.find_by_id(@proceso.proyecto_id)

    @actividades= @proceso.actividads.all

    @tipo_recursos=TipoRecurso.all.uniq

    respond_to do |format|
      format.html { render :layout => 'proyectos1'}# show.html.erb
      format.json { render json: @proceso }
    end
  end

  def Reportes
    @proceso=Proceso.find(params[:id_proceso])
    @duracion=(@proceso.proyecto.fecha_fin-@proceso.proyecto.fecha_inicio).to_i
    #@duracion=(@duracion/30).to_i

    @tipo_recursos=TipoRecurso.all

    if(!@proceso.proyecto.presupuesto)
      @proceso.proyecto.presupuesto = 0
    end
   # @proyecto=@proceso.proyecto.nombre
    # Crea un nuevo fichero, y escribe
    #app/views/procesos/
    File.open('app/views/procesos/template.tjp', 'w') do |f2|
    # '\n' es el retorno de carro
    f2.puts "
    project acso "+ "\""+@proceso.proyecto.nombre+ "\" "+@proceso.proyecto.fecha_inicio.to_s+" +"+@duracion.to_s+"d {
      # Set the default time zone for the project. If not specified, UTC
      # is used.
      timezone"+ "\""+ "America/Bogota" + "\""+ "
      # Hide the clock time. Only show the date.
      timeformat "+ "\""+ "%Y-%m-%d %H:%M:%S %z"+ "\""+"
      # Use US format for numbers
      numberformat "+ "\""+ "-"+ "\""+" "+ "\""+""+ "\""+" "+ "\""+","+ "\""+" "+ "\""+"."+ "\""+" 1
      # Use US financial format for currency values. Don't show cents.
      currencyformat "+ "\""+"("+ "\""+" "+ "\""+")"+ "\""+" "+ "\""+","+ "\""+" "+ "\""+"."+ "\""+" 0
      # Pick a day during the project that will be reported as 'today' in
      # the project reports. If not specified, the current day will be
      # used, but this will likely be outside of the project range, so it
      # can't be seen in the reports.
      now "+Time.now.strftime("%Y-%m-%d-%H:00")+"
      # The currency for all money values is the Euro.
      currency "+ "\""+"COP"+ "\""+"

      # We want to compare the baseline scenario to one with a slightly
      # delayed start.
      scenario plan "+ "\""+"Plan"+ "\""+" {
        scenario delayed "+ "\""+"Delayed"+ "\""+"
      }
      extend resource {
        text Phone "+ "\""+"Phone"+ "\""+"
      }
    }

    # The daily default rate of all resources. This can be overridden for each
    # resource. We specify this, so that we can do a good calculation of
    # the costs of the project.
    rate "+@proceso.proyecto.presupuesto.to_s+"


    # Register Good Friday as a global holiday for all resources.
    #leaves holiday "+ "\""+"Good Friday"+ "\""+" 2002-03-29
    flags equipo
    flags persona
    flags material
    flags cosas

    # This is one way to form teams
    macro allocate_developers [
      allocate dev1
      allocate dev2
      allocate dev3
    ]

# In order to do a simple profit and loss analysis of the project we
    # specify accounts. One for the development costs, one for the
    # documentation costs, and one account to credit the customer payments
    # to.
    account cost "+ "\""+"Project Cost"+ "\""+" {  "
    @tipo_recursos.each do |tipo_recurso|
      if tipo_recurso.unit==1
        f2.puts"account tipo_recH"+tipo_recurso.id.to_s+" "+ "\""+tipo_recurso.nombre.to_s+ "\""
      else
        f2.puts"account tipo_recM"+tipo_recurso.id.to_s+" "+ "\""+tipo_recurso.nombre.to_s+ "\""
      end
    end
    f2.puts"   }
    account rev "+ "\""+"Payments"+ "\""+"
    # The Profit&Loss analysis should be rev - cost accounts.
    balance cost rev


    resource boss "+ "\""+Usuario.find_by_id(@proceso.proyecto.director).nombre+ "\""+" {
    email "+ "\""+@proceso.proyecto.director.to_s+ "\""+"
    Phone  "+ "\""+@proceso.proyecto.director.to_s+ "\""+"
    rate "+@proceso.proyecto.presupuesto.to_s+"
    }"

    #RECURSOS
    @tipo_recursos.each do |tipo_recurso|
      if tipo_recurso.unit==1
        f2.puts "resource tipo_recH"+tipo_recurso.id.to_s+" "+ "\""+tipo_recurso.nombre.to_s+ "\""+" {"
        @proceso.proyecto.usuarios.each do |usuario|
          if usuario.tipo_recurso_id==tipo_recurso.id
            f2.puts "resource recH"+usuario.id.to_s+" "+ "\""+usuario.nombre.to_s+ "\""+" {
           email "+ "\""+usuario.nombre.to_s+ "\""+"
           Phone "+ "\""+usuario.nombre.to_s+ "\""+"
           rate "+usuario.tipo_recurso.cost.to_s+
          "flags persona}"
          end

        end
        f2.puts " flags equipo
            }"
      end
    end

    @tipo_recursos.each do |tipo_recurso|
      if tipo_recurso.unit==2
        f2.puts "resource tipo_recM"+tipo_recurso.id.to_s+" "+ "\""+tipo_recurso.nombre.to_s+ "\""+" {"
        @proceso.proyecto.recursos.each do |recurso|
          if recurso.tipo_recurso_id==tipo_recurso.id
           f2.puts "resource recM"+recurso.id.to_s+" "+ "\""+recurso.nombre.to_s+ "\""+" {
           #unidades "+ "\""+recurso.unidades.to_s+ "\""+"
           rate "+recurso.costo.to_s+
          "flags cosas }"
          end

        end
        f2.puts " flags material
            }"
      end
    end

    #TAREAS

    f2.puts " # Now we specify the work packages. The whole project is described as
              # a task that contains subtasks. These subtasks are then broken down
              # into smaller tasks and so on. The innermost tasks describe the real
              # work and have resources allocated to them. Many attributes of tasks
              # are inherited from the enclosing task. This saves you a lot of typing.
              task AcSo "+ "\""+"Accounting Software"+ "\""+" {

                # All work-related costs will be booked to this account unless the
                # subtasks specify something different.
                #chargeset dev
                # For the duration of the project we have running cost that are not
                # included in the labor cost.
                # charge 170 perday
                responsible boss
                "

    @proceso.tareas.each do |tarea|
      f2.puts "     task tarea"+tarea.id.to_s+" "+ "\""+tarea.nombre.to_s+ "\""+" {
                  priority "+tarea.prioridad.to_s+"
                  # Now we use the macro declared above to allocate the resources
                  # for this task. Because they can work in parallel, they may finish this
                  # task earlier than in 20 working-days."
      if tarea.usuarios.count>0
        f2.puts "# The effort to finish this task is 20 man-days.
                  effort "+tarea.duracion.to_s+"d"

                numRec=tarea.usuarios.count
                conta=0
                tarea.usuarios.each do |recurso|
                  if   conta==0
                    f2.puts "allocate "

                  end
                  f2.puts "recH" +recurso.id.to_s
                  conta=conta+1
                  if conta<numRec
                    f2.puts ","
                  end

                end


        numRecM=tarea.recursos.count
        contaM=0
        tarea.recursos.each do |recurso|
          if   conta==0 && contaM==0
            f2.puts "allocate "

          end
          if   conta>0 && contaM==0
            f2.puts ", "

          end
          f2.puts "recM" +recurso.id.to_s
          contaM=contaM+1
          if contaM<numRecM
            f2.puts ","
          end

        end

      end


      f2.puts"      # Each task without subtasks must have a start or an end
                  # criterion and a duration. For this task we use a reference to a
                  # milestone defined further below as the start criterion. So this task
                  # can not start before the specified milestone has been reached.
                  # References to other tasks may be relative. Each exclamation mark (!)
                  # means 'in the scope of the enclosing task'. To descent into a task, the
                  # fullstop (.) together with the id of the tasks have to be specified.
                  depends !deliveries.start"
      contador=0
      numtar=  TareaPresedencium.find_all_by_sucesora_id(tarea.id).count
      TareaPresedencium.find_all_by_sucesora_id(tarea.id).each do |presedencia|
        if   contador==0 && presedencia.predecesora_id.to_s !=''
          f2.puts "depends "

        end
        if    presedencia.predecesora_id.to_s !=''
          f2.puts "!tarea" +presedencia.predecesora_id.to_s
          contador=contador+1

        if contador<numtar
          f2.puts ","
        end
        end
      end
      if tarea.usuarios.count>0
        numUsu=tarea.usuarios.count
        contaUsu=0
        tarea.usuarios.each do |recurso|
          if   contaUsu==0
            f2.puts "  limits {"

          end
          dedica=TareaParticipante.find_by_tarea_id_and_usuario_id(tarea.id,recurso.id)
          f2.puts "dailymax " +dedica.dedicacion.to_s+"h {
                      resources recH" +recurso.id.to_s+"}"
          contaUsu=contaUsu+1
         end
        f2.puts "}"
      end
      f2.puts "}"
    end

    #MILESTONES
    f2.puts "task deliveries "+ "\""+"Milestones"+ "\""+" {

      # Some milestones have customer payments associated with them. We
      # credit these payments to the 'rev' account.
      purge chargeset
      chargeset rev

      task start "+ "\""+t('.inicio')+ "\""+" {
        # A task that has no duration is a milestone. It only needs a
        # start or end criterion. All other tasks depend on this task.
        # Here we use the built-in macro ${projectstart} to align the
        # start of the task with the above specified project time frame.
        start ${projectstart}
      # For some reason the actual start of the project got delayed.
      # We record this, so that we can compare the planned run to the
      # delayed run of the project.
      # delayed:start 2002-01-20
      # At the beginning of this task we receive a payment from the
      # customer. This is credited to the account associated with this
      # task when the task starts.
      charge 21000.0 onstart
    }


    }
    }"

    #REPORTES

    f2.puts " # Now the project has been specified completely. Stopping here would
                # result in a valid TaskJuggler file that could be processed and
                # scheduled. But no reports would be generated to visualize the
                # results.

                navigator navbar {
                  hidereport @none
                }

                macro TaskTip [
                  tooltip istask() -8<-
                    '''Start: ''' <-query attribute='start'->
                    '''End: ''' <-query attribute='end'->
                    ----
                    '''Resources:'''

                    <-query attribute='resources'->
                    ----
                    '''Precursors: '''

                    <-query attribute='precursors'->
                    ----
                    '''Followers: '''

                    <-query attribute='followers'->
                    ->8-
                ]

                textreport frame"+ "\""+"\""+" {
                  header -8<-
                   <[navigator id="+ "\""+"navbar"+ "\""+"]>
                  ->8-
                  footer "+ "\""+"----"+ "\""+"
                  textreport index "+ "\""+"Overview"+ "\""+" {
                    formats html
                    title "+ "\""+t('.principal')+ "\""+"
                    center '<[report id="+ "\""+"overview"+ "\""+"]>'
                  }

                  textreport development "+ "\""+"Development"+ "\""+" {
                    formats html
                    title "+ "\""+t('.desarrollo')+ "\""+"
                    center '<[report id="+ "\""+"development"+ "\""+"]>'
                  }

                  textreport "+ "\""+"ResourceGraph"+ "\""+" {
                    formats html
                    title "+ "\""+t('.recursosM')+ "\""+"
                    center '<[report id="+ "\""+"resourceGraph"+ "\""+"]>'
                  }
                  textreport "+ "\""+"Deliveries"+ "\""+" {
                    formats html
                    title "+ "\""+t('.entregables')+ "\""+"
                    center '<[report id="+ "\""+"deliveries"+ "\""+"]>'
                  }

                  textreport "+ "\""+"ContactList"+ "\""+" {
                    formats html
                    title "+ "\""+t('.recursoHumano')+ "\""+"
                    center '<[report id="+ "\""+"contactList"+ "\""+"]>'
                  }

                  textreport "+ "\""+"resourcesM"+ "\""+" {
                    formats html
                    title "+ "\""+t('.recursoMaterial')+ "\""+"
                    center '<[report id="+ "\""+"resourcesM"+ "\""+"]>'
                  }

                }

                # A traditional Gantt chart with a project overview.
                taskreport overview "+ "\""+"\""+" {
                  header -8<-
                    === "+t('.titulo')+" ===
                  ->8-
                  columns bsi { title 'WBS' },
                          name { title '"+ t('.nombre') + "' },
                          start { title "+ "\""+"Fecha inicio"+ "\""+" },
                          end { title "+ "\""+"Fecha fin"+ "\""+" },
                          effort { title "+ "\""+"Esfuerzo"+ "\""+" },
                          cost { title "+ "\""+"Costo"+ "\""+" },
                          revenue { title "+ "\""+"Ingresos"+ "\""+" },
                          chart { ${TaskTip} }
                  # For this report we like to have the abbreviated weekday in front
                  # of the date. %a is the tag for this.
                  timeformat "+ "\""+"%a %Y-%m-%d"+ "\""+"
                  loadunit days
                  hideresource @all
                  balance cost rev
                  caption '"+t('.comentario')+"'

                  #footer -8<-
                  #  === Staffing ===

                  #  All project phases are properly staffed. See [[ResourceGraph]] for
                  #  detailed resource allocations.

                  #  === Current Status ===

                  #  The project started off with a delay of 4 days. This slightly affected
                  #  the original schedule. See [[Deliveries]] for the impact on the
                  #  delivery dates.
                  #->8-
                }

                # Macro to set the background color of a cell according to the alert
                # level of the task.
                macro AlertColor [
                  cellcolor plan.alert = 0 "+ "\""+"#00D000"+ "\""+" # green
                    cellcolor plan.alert = 1 "+ "\""+"#D0D000"+ "\""+" # yellow
                    cellcolor plan.alert = 2 "+ "\""+"#D00000"+ "\""+" # red
                    ]

                    taskreport status "+ "\""+"\""+" {
                      columns bsi { width 50 title 'WBS' }, name { width 150 },
                              start { width 100 }, end { width 100 },
                               effort { width 100 },
                               alert { tooltip plan.journal
                               != '' "+ "\""+"<-query attribute='journal'->"+ "\""+" width 150 },
                               status { width 150 }
                    scenarios delayed

                    taskreport dashboard "+ "\""+"\""+" {
                      headline "+ "\""+"Project Dashboard (<-query attribute='now'->)"+ "\""+"
                      columns name { title "+ "\""+"Task"+ "\""+" ${AlertColor} width 200},
                               resources { width 200 ${AlertColor}
                    listtype bullets
                    listitem "+ "\""+"<-query attribute='name'->"+ "\""+"
                    start ${projectstart} end ${projectend} },
                        alerttrend { title "+ "\""+"Trend"+ "\""+" ${AlertColor} width 50 },
                        journal { width 350 ${AlertColor} }
                    journalmode status_up
                    journalattributes headline, author, date, summary, details
                    hidetask ~hasalert(0)
                    sorttasks alert.down, delayed.end.up
                    period %{${now} - 1w} +1w
                    }
                    taskreport completed "+ "\""+"\""+" {
                      headline "+ "\""+"Already completed tasks"+ "\""+"
                      hidetask ~(delayed.end <= ${now})
                    }
                    taskreport ongoing "+ "\""+"\""+" {
                      headline "+ "\""+"Ongoing tasks"+ "\""+"
                      hidetask ~((delayed.start <= ${now}) & (delayed.end > ${now}))
                    }
                    taskreport future "+ "\""+"\""+" {
                      headline "+ "\""+"Future tasks"+ "\""+"
                      hidetask ~(delayed.start > ${now})
                    }
                    }

                # A list of tasks showing the resources assigned to each task.
                    taskreport development "+ "\""+"\""+" {
                      scenarios delayed
                      headline "+ "\""+ t('.tituloG') + "\""+"
                      columns
                      bsi { title 'WBS' },
                      name { title '"+ t('.nombre') + "' },
                      start { title "+ "\""+"Fecha inicio"+ "\""+" },
                      end { title "+ "\""+"Fecha fin"+ "\""+" },
                      effort { title "+ "\""+"Trabajo"+ "\""+" },
                      duration { title "+ "\""+"Duracion"+ "\""+" },
                      chart { ${TaskTip} scale day width 500 }
                      timeformat "+ "\""+"%Y-%m-%d"+ "\""+"
                      hideresource ~(isleaf() & isleaf_())
                      sortresources name.up
                    }

                # A list of all tasks with the percentage completed for each task
                    taskreport deliveries "+ "\""+"\""+" {
                      headline "+ "\""+"Entregables del proceso"+ "\""+"
                      columns bsi { title 'WBS' },
                      name { title "+ "\""+"Nombre"+ "\""+" },
                      start { title "+ "\""+"Fecha inicio"+ "\""+" },
                      end { title "+ "\""+"Fecha fin"+ "\""+" },
                      note { title 'Nota' width 150 },
                      complete { title "+ "\""+"Avance"+ "\""+" },
                      chart { ${TaskTip} }
                      taskroot AcSo.deliveries
                      hideresource @all
                      scenarios plan, delayed
                    }
                # A list of all employees with their contact details.
                    resourcereport contactList "+ "\""+"\""+" {
                      scenarios delayed
                      headline "+ "\""+"Lista de contactos"+ "\""+"
                      columns name { title "+ "\""+"Nombre"+ "\""+" },
                              email { celltext 1 "+ "\""+"[mailto:<-email-> <-email->]"+ "\""+" },
                              Phone { title "+ "\""+"Telefono"+ "\""+" },
                              managers { title "+ "\""+"Jefe"+ "\""+" },
                              chart { scale day }
                      hideresource  ~persona
                      sortresources name.up
                      hidetask @all
                    }

                 # A list of all employees with their contact details.
                    resourcereport resourcesM "+ "\""+"\""+" {
                      scenarios delayed
                      headline "+ "\""+"Utilizacion de recursos"+ "\""+"
                      columns name { title "+ "\""+"Nombre"+ "\""+" },
                      chart { scale day }
                      hideresource  ~cosas
                      sortresources name.up
                      hidetask @all
                    }

                # A graph showing resource allocation. It identifies whether each
                # resource is under- or over-allocated for.
                    resourcereport resourceGraph "+ "\""+"\""+" {
                      scenarios delayed
                      headline "+ "\""+"Asignacion de recursos"+ "\""+"
                      columns no,
                      name { title "+ "\""+"Nombre"+ "\""+" },
                      effort { title "+ "\""+"Duracion"+ "\""+" },
                      rate { title "+ "\""+"Costo/dia"+ "\""+" },
                      weekly { ${TaskTip} }
                      loadunit shortauto
                      # We only like to show leaf tasks for leaf resources.
                      hidetask ~(isleaf() & isleaf_())
                      sorttasks plan.start.up
                  }

export" + "\""+"MS-Project"+ "\""+" {
  formats mspxml
  loadunit quarters
}
                   "
   end

		if RUBY_PLATFORM =~ /linux/ then
			system("export LC_CTYPE=en_US.UTF-8")
			#system("export LC_CTYPE=en_US.ISO8859-1")
			
			system("rm app/views/procesos/*html")
			
			system("tj3 app/views/procesos/template.tjp")
			puts Dir.pwd
			@dir=Dir.pwd.to_s
			
			system("ls -lt ./*html")
			system("mv ./Overview.html app/views/procesos/Overview.html")
			system("mv ./ContactList.html app/views/procesos/ContactList.html")
			system("mv ./Deliveries.html app/views/procesos/Deliveries.html")
			system("mv ./Development.html app/views/procesos/Development.html")
			system("mv ./ResourceGraph.html app/views/procesos/ResourceGraph.html")
      system("mv ./resourcesM.html app/views/procesos/resourcesM.html")
			
			system("ls -lt app/views/procesos/*html")
		else

			system("tj3 app/views/procesos/template.tjp")
			puts Dir.pwd
			@dir=Dir.pwd.to_s
			
			FileUtils.move 'Overview.html', @dir+'\\app\\views\\procesos\\Overview.html'
			FileUtils.move 'ContactList.html', @dir+'\\app\\views\\procesos\\ContactList.html'
			FileUtils.move 'Deliveries.html', @dir+'\\app\\views\\procesos\\Deliveries.html'
			FileUtils.move 'Development.html', @dir+'\\app\\views\\procesos\\Development.html'
			FileUtils.move 'ResourceGraph.html', @dir+'\\app\\views\\procesos\\ResourceGraph.html'
      FileUtils.move 'resourcesM.html', @dir+'\\app\\views\\procesos\\resourcesM.html'
		end
	
    	render :template => 'procesos/Overview', :layout => 'reportes'
  end
  def Overview

   render :template => 'procesos/Overview', :layout => 'reportes'
  end
  def Status
    render :template => 'procesos/Status', :layout => 'reportes'
  end
  def ResourceGraph
    render :template => 'procesos/ResourceGraph', :layout => 'reportes'
  end
  def resourcesM
    render :template => 'procesos/resourcesM', :layout => 'reportes'
  end
  def Workpackage1
    render :template => 'procesos/Work package 1', :layout => 'reportes'
  end
  def Workpackage2
    render :template => 'procesos/Work package 2', :layout => 'reportes'
  end
  def ContactList
    render :template => 'procesos/ContactList', :layout => 'reportes'
  end
  def Deliveries
    render :template => 'procesos/Deliveries', :layout => 'reportes'
  end
  def Development
    render :template => 'procesos/Development', :layout => 'reportes'
  end

  # GET /procesos/new
  # GET /procesos/new.json

  def change_tipoPlantilla #Funcion Ajax que modificara el combo de plantillas
    @obj_proceso = Proceso.new()
    @list_plantillas = Plantillas.find(:all,:conditions=>{:tipo_plantilla_id=>params[:tipo_plantilla_id_id].to_i})

    #change_companies.rjs
    page.replace_html("list_plantillas",:partial=>"select_plantillas")
  end

  def getTipoPlantilla

    @data_for_select2 = TipoPlantilla.all

    #render :json =>"{"+@comilla+"1"+@comilla+":"+@comilla+"Alto Orinoco"+@comilla+","+@comilla+"2"+@comilla+":"+@comilla+"Huachamacare"+@comilla+"}"
    @c= params[:callback]

    @tam=@data_for_select2.length
    @i=1
    @data = @c+"({"+"\""
    @data_for_select2.each do |select|

      @data  = @data+select.id.to_s+"\""+":"+"\""+select.nombre+"\""

      if @tam!=@i
        @data=@data+","+"\""
      else
        @data=@data+"})"
      end
      @i=@i+1
    end
    #3143216669

  #  @data=@c+"({"+"\""+"1"+"\""+":"+"\""+"Hola"+"\""+","+"\""+"3"+"\""+":"+"\""+"Chao"+"\""+"})"
    #@data=TipoPlantilla.all.map{|p| [p.id.to_s,p.id.to_s+":"+p.nombre] }
    #render :json => @data_for_select2.map{|c| [c.id.to_s(), c.nombre] }
    render :text => @data

  end


  def getdata

    @comilla='"';
    @data_for_select1 = params[:tipo_plantilla]

    @data_for_select2 = Plantilla.where(:tipo_plantilla_id => @data_for_select1).all
    @c= params[:callback]

    @tam=@data_for_select2.length
    @i=1
    if @tam!=0

    @data = @c+"({"+"\""

    @data_for_select2.each do |select|

      @data  = @data+select.id.to_s+"\""+":"+"\""+select.nombre+"\""

      if @tam!=@i
        @data=@data+","+"\""
      else
        @data=@data+"})"
      end

      @i=@i+1

    end

    else
        @data=""
    end

    render :json => @data

  end

  def new

    @proceso = Proceso.new

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @proceso }
    end
  end

  # GET /procesos/1/edit
  def edit
    @proceso = Proceso.find(params[:id])
  end

  # POST /procesos
  # POST /procesos.json
  def create
    @proceso = Proceso.new(params[:proceso])
    @proceso.proyecto_id=params[:proyecto_id]
    @proceso.tipo_plantilla_id=params[:proceso_tipo_plantilla]
    @id_plantilla = params[:plantilla]

    @proyecto = Proyecto.find(params[:proyecto_id])
    @procesos= Proceso.find_all_by_proyecto_id(:proyecto_id)

    respond_to do |format|
      if @proceso.save

        clonar_plantilla( @id_plantilla, @proceso.id )

        format.html { redirect_to @proceso, notice: 'Proceso was successfully created.' }
        format.json { render json: @proceso, status: :created, location: @proceso }
      else
        format.html { render action: "new" }
        format.json { render json: @proceso.errors, status: :unprocessable_entity }
      end
    end
  end

  # PUT /procesos/1
  # PUT /procesos/1.json
  def update
    @proceso = Proceso.find(params[:id])

    respond_to do |format|
      if @proceso.update_attributes(params[:proceso])
        format.html { redirect_to @proceso, notice: 'Proceso was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @proceso.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /procesos/1
  # DELETE /procesos/1.json
  def destroy
    @proceso = Proceso.find(params[:id])
    @proceso.destroy

    respond_to do |format|
      format.html { redirect_to procesos_url }
      format.json { head :no_content }
    end
  end

  def clonar_plantilla(id_plantilla, id_proceso)

    @id_plantilla = id_plantilla
    @id_proceso = id_proceso

    @plantilla = Plantilla.find(@id_plantilla)

      @my_js_all_tress = Array.new
      @my_js_all_oldnew = Hash.new

      @my_js_tree_origen = MyJsTree.find_by_plantilla_id(@plantilla.id)
      @my_js_tree = MyJsTree.new(
          :parent_id => 0,
          :position => @my_js_tree_origen.position,
          :left => @my_js_tree_origen.left,
          :right => @my_js_tree_origen.right,
          :title => @my_js_tree_origen.title,
          :type => @my_js_tree_origen.type,
          :level => @my_js_tree_origen.level,
          :proceso_id => Proceso.last().id
      )

      @my_js_tree.save!

      @my_js_all_tress.push @my_js_tree
      @my_js_all_oldnew[@my_js_tree_origen.id] = MyJsTree.last().id

      @actividades = Actividad.find_all_by_plantilla_id(@id_plantilla)

      @actividades.each do |origen_act|

        @my_js_tree_origen = MyJsTree.find(origen_act.my_js_tree_id)
        @my_js_tree = MyJsTree.new(
            :parent_id => @my_js_tree_origen.parent_id,
            :position => @my_js_tree_origen.position,
            :left => @my_js_tree_origen.left,
            :right => @my_js_tree_origen.right,
            :title => @my_js_tree_origen.title,
            :type => @my_js_tree_origen.type,
            :level => @my_js_tree_origen.level,
            :proceso_id => Proceso.last().id
        )

        @my_js_tree.save!

        @my_js_all_tress.push @my_js_tree
        @my_js_all_oldnew[@my_js_tree_origen.id] = MyJsTree.last().id

        @actividad = Actividad.new(
          :nombre => origen_act.nombre,
          :descripcion => origen_act.descripcion,
          :modoejecucion => origen_act.modoejecucion,
          :duracion => origen_act.duracion,
          :num_instancias => 1,
          :proceso_id => Proceso.last().id,
          :my_js_tree_id => MyJsTree.last().id
        )

        if(@actividad.save!)

            @act_tipo_recursos = ActividadTiporecurso.find_all_by_actividad_id(origen_act.id)

            @act_tipo_recursos.each do |origen_acttiporec|
               @act_tipo_recurso = ActividadTiporecurso.new(
                  :actividad_id =>  Actividad.last().id,
                  :tipo_recurso_id => origen_acttiporec.tipo_recurso_id,
                  :cantidad => origen_acttiporec.cantidad
               )

               @act_tipo_recurso.save!

            end

            @act_tipo_artefactos = ActividadTipoartefacto.find_all_by_actividad_id(origen_act.id)

            @act_tipo_artefactos.each do |origen_acttipoart|
              @act_tipo_artefacto = ActividadTipoartefacto.new(
                :actividad_id =>  Actividad.last().id,
                :tipo_artefacto_id => origen_acttipoart.tipo_artefacto_id,
                :modo => origen_acttipoart.modo
              )

              @act_tipo_artefacto.save!

             end
        end

      end

      @compuertus = Compuertu.find_all_by_plantilla_id(@id_plantilla)

      @compuertus.each do |origen_com|

        @my_js_tree_origen = MyJsTree.find(origen_com.my_js_tree_id)
        @my_js_tree = MyJsTree.new(
            :parent_id => @my_js_tree_origen.parent_id,
            :position => @my_js_tree_origen.position,
            :left => @my_js_tree_origen.left,
            :right => @my_js_tree_origen.right,
            :title => @my_js_tree_origen.title,
            :type => @my_js_tree_origen.type,
            :level => @my_js_tree_origen.level,
            :proceso_id => Proceso.last().id
        )

        @my_js_tree.save!

        @my_js_all_tress.push @my_js_tree
        @my_js_all_oldnew[@my_js_tree_origen.id] = MyJsTree.last().id

        @compuertu = Compuertu.new(
            :nombre => origen_com.nombre,
            :descripcion => origen_com.descripcion,
            :tipo => origen_com.tipo,
            :desicion => origen_com.desicion,
            :proceso_id => Proceso.last().id ,
            :my_js_tree_id => MyJsTree.last().id
        )

      @compuertu.save!

      end

      @eventos = Evento.find_all_by_plantilla_id(@id_plantilla)

      @eventos.each do |origen_eve|

        @my_js_tree_origen = MyJsTree.find(origen_eve.my_js_tree_id)

        @my_js_tree = MyJsTree.new(
            :parent_id => @my_js_tree_origen.parent_id,
            :position => @my_js_tree_origen.position,
            :left => @my_js_tree_origen.left,
            :right => @my_js_tree_origen.right,
            :title => @my_js_tree_origen.title,
            :type => @my_js_tree_origen.type,
            :level => @my_js_tree_origen.level,
            :proceso_id => Proceso.last().id
        )

        @my_js_tree.save!

        @my_js_all_tress.push @my_js_tree
        @my_js_all_oldnew[@my_js_tree_origen.id] = MyJsTree.last().id

        @evento = Evento.new(
            :nombre => origen_eve.nombre,
            :tipo => origen_eve.tipo,
            :proceso_id => Proceso.last().id,
            :my_js_tree_id => MyJsTree.last().id
        )

      @evento.save!

      end

      @rutas = Rutum.find_all_by_plantilla_id(@id_plantilla)

      @rutas.each do |origen_rut|

        @my_js_tree_origen = MyJsTree.find(origen_rut.my_js_tree_id)

        @my_js_tree = MyJsTree.new(
            :parent_id => @my_js_tree_origen.parent_id,
            :position => @my_js_tree_origen.position,
            :left => @my_js_tree_origen.left,
            :right => @my_js_tree_origen.right,
            :title => @my_js_tree_origen.title,
            :type => @my_js_tree_origen.type,
            :level => @my_js_tree_origen.level,
            :proceso_id => Proceso.last().id
        )

        @my_js_tree.save!

        @my_js_all_tress.push @my_js_tree
        @my_js_all_oldnew[@my_js_tree_origen.id] = MyJsTree.last().id

        @ruta = Rutum.new(
            :nombre => origen_rut.nombre,
            :tipo => origen_rut.tipo,
            :proceso_id => Proceso.last().id,
            :my_js_tree_id => MyJsTree.last().id
        )

        @ruta.save!

      end


      @my_js_all_tress.each do |js_tree|
        js_tree.parent_id = @my_js_all_oldnew[js_tree.parent_id]
        js_tree.save!

      end
  end

  def duracion

  end
end
